<template>
  <div class="plugin-reports-goods">
    <div class="bg-box">
      <div class="right">
        <t-radio-group size="small" variant="default-filled" v-model="type" @change="onTotal">
          <t-radio-button v-for="(item, index) in plugin.tm('goods.right')" :value="index">{{ item }}</t-radio-button>
        </t-radio-group>
      </div>
      <div class="title">
        {{ plugin.t('goods.title') }}
      </div>
      <Table :goods="goods" :page="page" @change="onPage" />
    </div>
  </div>
</template>
<script setup>
  import { ref, reactive, watch } from 'vue'
  import app from '@/app'
  import index from '../../index'
  import { limit } from '@/api/store/goods'
  import Table from './table.vue'

  const plugin = index.plugin
  const props = defineProps(['factory', 'data'])

  const factory = props.factory
  const list = ref([])
  const type = ref(0)
  const goods = ref({})
  const page = reactive({
    list: [],
    current: 1,
    pageSize: 20,
    total: 0,
    showPageSize: false,
    loading: false
  })
  const sort = [
    (a, b) => b.gc - a.gc, 
    (a, b) => b.m - a.m, 
    (a, b) => b.pm - a.pm
  ]

  // 拉取统计数据
  const onTotal = () => {
    list.value = [...props.data]
    list.value.sort(sort[type.value])
    onPage(1)
  }

  // 切换分页
  const onPage = async (current) => {
    page.loading = true
    page.current = current
    page.total = list.value.length
    // 截取数组
    page.list = list.value.slice((current - 1) * page.pageSize, current * page.pageSize)
    // 加载商品
    if(page.list.length) {
      const goodsList = {}
      const res = await limit({ id: page.list.map(item => item.id), select: ['id', 'name', 'code'] })
      res.forEach(item => {
        goodsList[item.id] = item
      })
      goods.value = goodsList
    }
    page.loading = false
  }

  // 监听
  watch(props, () => {
    onTotal()
  })

  onTotal()
</script>
<style lang="scss">
  @import '@/style/global';

  .plugin-reports-goods{

  }
</style>